﻿using System;
using System.Runtime.Remoting.Messaging;
using System.Diagnostics;

namespace Skynet.CommonLibrary.AOP.MontiorLog
{
    internal class MontiorLogAopSink : IBeforeHandle, IAfterHandle
    {
        readonly Stopwatch _watch;
        readonly MontiorLogAopAttribute _contextAttribute;
        public MontiorLogAopSink(MontiorLogAopAttribute contextAttribute)
        {
            _watch = new Stopwatch();
            _contextAttribute = contextAttribute;
        }

        private string _mothodName;
        private string _className;

        #region IBeforeHandle 成员

        public void SyncBeforeProcess(IMethodCallMessage call)
        {
            _watch.Reset();
            _watch.Start();
            _mothodName = call.MethodName ;
            if (call.MethodBase.DeclaringType != null) 
                _className = call.MethodBase.DeclaringType.Name;
        }

        #endregion

        #region IAfterHandle 成员

        public IMessage SyncAfterProcess(MethodReturnMessageWrapper replyMsg)
        {
            _watch.Stop();
            if (_watch.ElapsedMilliseconds * 1000 > _contextAttribute.FilterSecond)
            {
                string montiorMsg = string.Format("触发方位:{0},费时:{1}", _className + "." + _mothodName, _watch.ElapsedMilliseconds);
                Console.WriteLine(montiorMsg);
            }
            return replyMsg;
        }

        #endregion

    }
}
